package com.download.zhuaba.Controller;

import com.download.zhuaba.Dao.UserRepository;
import com.download.zhuaba.Entity.User;
import com.download.zhuaba.Utils.enCodeByBase64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class RegisterController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping("/register.html")
    public String login() {
        return "register";
    }

    @RequestMapping(value = "/RegisterController", method = RequestMethod.POST)
    public String registerAdmin(@RequestParam("Username") String Username, @RequestParam("Password") String Password, @RequestParam("Email") String Email, RedirectAttributes attr) throws Exception {
        List<User> list = new ArrayList<User>();
        list = userRepository.findAll();
        if (list != null) {
            for (User user1 : list) {
                if (user1.getEmail().equals(Email) || user1.getUsername().equals(Username)) {
                    attr.addFlashAttribute("flag", "0");//跳转地址不带上u2参数
                        return "redirect:http://localhost:8080/register.html";
                }
            }
        }
        User user = new User();
        user.setUsername(Username);
        user.setEmail(Email);
        enCodeByBase64 encode=new enCodeByBase64();
        Password = encode.enCode(Password);
        user.setPassword(Password);
        userRepository.save(user);
        attr.addFlashAttribute("flag", "1");//跳转地址不带上u2参数
        return "redirect:http://localhost:8080/";
    }
}